//
//  AddressListVC.m
//  MyNewProject
//
//  Created by sun on 2019/2/2.
//  Copyright © 2019 sun. All rights reserved.
//

#import "AddressListVC.h"
#import "AddAddressVC.h"
#import "AddressCell.h"
#import "MJRefresh.h"
#import "XM_AuctionProductModel.h"
@interface AddressListVC ()<UITableViewDelegate,UITableViewDataSource>{
    NSInteger page;
    NSIndexPath * isDefaultIndex;//默认地址的 索引
}
@property(nonatomic,strong)UITableView * myTalbleView;
@property(nonatomic,strong)NSMutableArray * myData;

// 无数据
@property (nonatomic, strong) UIImageView *nodataImageView;
@property (nonatomic, strong) UILabel *nodataLabel;
@end

@implementation AddressListVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.gk_navTitle = @"收货地址";
    [self.view addSubview:self.myTalbleView];
    UIFont * font1 = SKFONT_BOLD_SIZE(18);
    UIButton *button1 = [UIButton buttonWithType:UIButtonTypeCustom];
    button1.frame = CGRectMake(0, SCREENH_HEIGHT -50 - SKBottomSafe_Height, SCREEN_WIDTH , 50);
    [button1 setTitle:@"新增地址" forState:UIControlStateNormal];
    button1.backgroundColor = SKColorWithHex(0xE33030);
    button1.titleLabel.font = font1 ;
    [button1 setTitleColor:SKColorWithHex(0xFFFFFF) forState:UIControlStateNormal];
    [button1 addTarget:self action:@selector(addAdressDeal:) forControlEvents:UIControlEventTouchUpInside];
    [self.view  addSubview:button1];
    [self addNodataView];
    page = 1;
    [self requestData];
}

- (void)addNodataView {
    [self.nodataImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.mas_offset(CGPointMake(0, -40));
    }];
    [self.nodataLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.nodataImageView);
        make.top.mas_equalTo(self.nodataImageView.mas_bottom).mas_offset(20);
    }];
    
}
-(void)requestData{
    NSDictionary *param = @{
        @"uid":self.uid,
        @"loginKey":self.loginKey,
        @"page":@(page)
    };
    [YQNetworking postWithUrl:@"My/getAddrList" params:param reloginRefreshBlock:^(id response) {
    } successBlock:^(id response) {
        [self.myTalbleView.mj_header endRefreshing];
        [self.myData removeAllObjects];
        NSArray * dataArray = response[@"data"];
        for (NSDictionary * dic in dataArray) {
            XM_MyAddressModel * pModel =  [XM_MyAddressModel modelWithDictionary:dic];
            [self.myData addObject:pModel];
        }
        [self.myTalbleView reloadData];
    } failBlock:^(NSError *error) {
        [self.myTalbleView.mj_header endRefreshing];
    }];
}
-(NSMutableArray *)myData
{
    if (_myData == nil) {
        _myData = [NSMutableArray array];
    }
    self.nodataImageView.hidden = _myData.count > 0;
    self.nodataLabel.hidden = _myData.count > 0;
    return _myData;
}
-(UITableView*)myTalbleView
{

    if (_myTalbleView ==nil) {
        _myTalbleView =[[UITableView alloc] initWithFrame:CGRectMake(0,SKTopBar_Height ,SCREEN_WIDTH , SCREENH_HEIGHT-SKTopBar_Height-40 - SKBottomSafe_Height) style:UITableViewStyleGrouped];
        _myTalbleView.dataSource = self;
        _myTalbleView.delegate = self;
        _myTalbleView.estimatedRowHeight = 0;
        _myTalbleView.estimatedSectionFooterHeight = 0;
        _myTalbleView.estimatedSectionHeaderHeight = 0;
        _myTalbleView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _myTalbleView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            self->page = 1;
            [self requestData];
        }];
        if (@available(iOS 11.0, *)) {
            
            _myTalbleView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
            
        } else {
            
            self.automaticallyAdjustsScrollViewInsets = NO;
            
        }
    }
    return _myTalbleView;
}
- (UIImageView *)nodataImageView {
    if (!_nodataImageView) {
        _nodataImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"mine_address_nodata_status_img"]];
        [self.view addSubview:_nodataImageView];
    }
    return _nodataImageView;
}
- (UILabel *)nodataLabel {
    if (!_nodataLabel) {
        _nodataLabel = [[UILabel alloc] init];
        _nodataLabel.textColor = SKColorWithHex(0x888888);
        _nodataLabel.font = SKFONT_BOLD_SIZE(18);
        _nodataLabel.text = @"暂无收货地址";
        [self.view addSubview:_nodataLabel];
    }
    return _nodataLabel;
}
#pragma mark -  UITableView 代理相关

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.myData.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    XM_MyAddressModel * pModel = (XM_MyAddressModel *)self.myData[indexPath.section];
    AddressCell * cell =[tableView dequeueReusableCellWithIdentifier:@"AddressCell"];
    if (!cell) {
        
        cell = [[AddressCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"AddressCell"];
    }
    if (isDefaultIndex) {//重新设置的
        [cell.selectBtn setImage:indexPath == isDefaultIndex?SKIMAGE_NAMED(@"defaultSelected"):SKIMAGE_NAMED(@"unSelectedState") forState:UIControlStateNormal];
    }else{
        [cell.selectBtn setImage:[pModel.is_default isEqualToString:@"1"]?SKIMAGE_NAMED(@"defaultSelected"):SKIMAGE_NAMED(@"unSelectedState") forState:UIControlStateNormal];
    }
    cell.model = pModel;
    __weak typeof(self)weakSelf = self;
    cell.myDefaultSetup = ^(id model, AddressCell *cell) {
        
        [YQNetworking postWithUrl:@"My/setAddrDefault" params:@{@"uid":self.uid,@"loginKey":self.loginKey,@"id":pModel.addrId} reloginRefreshBlock:^(id response) {
            
        } successBlock:^(id response) {
            self->isDefaultIndex = indexPath;
            [weakSelf.myTalbleView reloadData];
        } failBlock:^(NSError *error) {
            
        }];
        
    };
    cell.myDeleteEvent = ^(id model, AddressCell *cell) {
        [YQNetworking postWithUrl:@"My/addrDel" params:@{@"uid":self.uid,@"loginKey":self.loginKey,@"id":pModel.addrId} reloginRefreshBlock:^(id response) {
            
        } successBlock:^(id response) {
            [weakSelf.myData removeObjectAtIndex:indexPath.section];
            [weakSelf.myTalbleView reloadData];
        } failBlock:^(NSError *error) {
            
        }];
    };
    cell.myEditing = ^(id model, AddressCell *cell) {
        AddAddressVC * addAddressVC =[AddAddressVC new];
        addAddressVC.isEdit = YES;
        addAddressVC.addressModel = pModel;
        addAddressVC.xm_block = ^{
            self->page = 1;
            [weakSelf requestData];
        };
        [weakSelf.navigationController pushViewController:addAddressVC animated:YES];
    };
    
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    return [AddressCell heightOfRowWithModel:self.myData[indexPath.section]];
    
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    return nil;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    return nil;
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    
    return CGFLOAT_MIN;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    
    return 10;
    //    return CGFLOAT_MIN;
    
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.kindOfType == 1) {
        XM_MyAddressModel * pModel = (XM_MyAddressModel *)self.myData[indexPath.section];

        if (self.myAdressList) {
            
            self.myAdressList(pModel);
            [self.navigationController popViewControllerAnimated:YES];
        }
    }
    
    
    
}


//tableView自带的左滑删除
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return YES;
    
}
// 定义编辑样式
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
    return UITableViewCellEditingStyleDelete;
    
    
}
// 进入编辑模式，按下出现的编辑按钮后,进行删除操作
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        XM_MyAddressModel * pModel = (XM_MyAddressModel *)self.myData[indexPath.section];
        __weak typeof(self)weakSelf = self;
        
        [YQNetworking postWithUrl:@"My/addrDel" params:@{@"uid":self.uid,@"loginKey":self.loginKey,@"id":pModel.addrId} reloginRefreshBlock:^(id response) {
            
        } successBlock:^(id response) {
            [weakSelf.myData removeObjectAtIndex:indexPath.section];
            [weakSelf.myTalbleView reloadData];
        } failBlock:^(NSError *error) {
            
        }];
    }
}
// 修改编辑按钮文字
- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return @"删除";
    
}


#pragma mark -- 没收收货地址的界面
-(void)notAdressLayout
{
    
    NSString * totalAmtStr =@"暂无收货地址";
    UIFont * font = SKFONT_Semibold(18);
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    
    button.frame = CGRectMake(0, 0, SCREEN_WIDTH , 160);
    
    button.center = CGPointMake(SCREEN_WIDTH/2, SCREENH_HEIGHT/2);
    
    button.imageView.contentMode = UIViewContentModeScaleAspectFit;
    
    
    
    [button setTitle:totalAmtStr forState:UIControlStateNormal];
    
    button.titleLabel.font = font ;
    
    [button setTitleColor:SKColorWithHex(0x888888) forState:UIControlStateNormal];
    
    [button setImage:SKIMAGE_NAMED(@"addressMissing") forState:UIControlStateNormal];
    [button setImagePosition:LXMImagePositionTop spacing:20];
    
    //    [button addTarget:self action:@selector(eventDeal:) forControlEvents:UIControlEventTouchUpInside];
    
    [self.view  addSubview:button];
    
    
    
    
    
}
#pragma mark -- 增加收货地址
-(void)addAdressDeal:(UIButton *)sender
{
    AddAddressVC * addAddressVC =[AddAddressVC new];
    addAddressVC.xm_block = ^{
        self->page = 1;
        [self requestData];
    };
    [self.navigationController pushViewController:addAddressVC animated:YES];
}
/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
